package com.everflourish.yeah100.act.questionlib;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.everflourish.yeah100.R;
import com.everflourish.yeah100.act.base.BaseActivity;
import com.everflourish.yeah100.adapter.QuestionAdapter;
import com.everflourish.yeah100.entity.question.Question;
import com.everflourish.yeah100.http.QuestionRequest;
import com.everflourish.yeah100.ui.AutoLoadRecylerView;
import com.everflourish.yeah100.ui.animator.CustomItemAnimator;
import com.everflourish.yeah100.utils.ImageSelectHolder;
import com.everflourish.yeah100.utils.IntentUtil;
import com.everflourish.yeah100.utils.LogUtil;
import com.everflourish.yeah100.utils.MyToast;
import com.everflourish.yeah100.utils.constant.Constant;
import com.everflourish.yeah100.utils.constant.PaperType;
import com.everflourish.yeah100.utils.constant.ResultCode;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.yalantis.ucrop.UCrop;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

/**
 * 作者：Created by liqisi on 2016/7/19.
 * 时间：2016/7/19
 */
public class QuestionListActivity extends BaseActivity implements AutoLoadRecylerView.LoadMoreListener {

    private Toolbar mToolBar;
    private AutoLoadRecylerView mQuestionRecylerView;
    public SwipeRefreshLayout mSwipeRefreshLayout;
    public SwipeRefreshLayout.OnRefreshListener mRefreshListener;
    private TextView mEmptyTv;
    private QuestionAdapter mAdapter;
    private List<Question> mList;
    public QuestionRequest mRequest;
    private String mExaminationId;
    public ImageSelectHolder mImageSelectHolder;
    private boolean isLoadMore = false;  // 是否加载更多
    private boolean isRefreshOrLoadMore = false;  // 是否在刷新或者加载
    public int upLoadType = 0;  // 0.题目图片上传  1.图片增加
    private String searchText;
    private com.lapism.searchview.SearchView mSearchView;

    /**
     * 每次加载10条
     */
    private int mSelectCount = 10;
    /**
     * 加载的位置
     */
    private int mStartIndex = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_question_list);
        initData();
        initView();
        configView();
        setSearchView();
    }

    private void initData() {
        mRequest = QuestionRequest.getInstance();
        mExaminationId = (String) getIntent().getSerializableExtra(
                IntentUtil.QUESTIONLIST);
        mList = new ArrayList<Question>();
        mAdapter = new QuestionAdapter(mContext, this, mList, mExaminationId, mQueue);
        mImageSelectHolder = new ImageSelectHolder(this);
    }

    private void initView() {
        mEmptyTv = (TextView) findViewById(R.id.question_empty_tv);
        mToolBar = (Toolbar) findViewById(R.id.toolbar_question_list);
        mSearchView = (com.lapism.searchview.SearchView) findViewById(R.id.question_searchView);
        mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.question_list_swipe);
        mQuestionRecylerView = (AutoLoadRecylerView) findViewById(R.id.question_list);
        mToolBar.setTitle("题目");
        setSupportActionBar(mToolBar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        mToolBar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finishMenuActivity();
            }
        });
        /*mToolBar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.question_upload:
                        upLoadType = 0;
                        mImageSelectHolder.open(mToolBar);
                        break;
                }
                return true;
            }
        });*/
    }

    private void configView() {
        mQuestionRecylerView.setLayoutManager(new LinearLayoutManager(this));
        mQuestionRecylerView.setItemAnimator(new CustomItemAnimator());
        mQuestionRecylerView.setAdapter(mAdapter);
        mRefreshListener = new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                searchText = "";
                getQuestionList();
            }
        };
        mSwipeRefreshLayout.setColorScheme(R.color.question_appbar_Accent);
        mSwipeRefreshLayout.setOnRefreshListener(mRefreshListener);
        mSwipeRefreshLayout.post(new Runnable() {
            @Override
            public void run() {
                mSwipeRefreshLayout.setRefreshing(true);
            }
        });
        mRefreshListener.onRefresh();
        mQuestionRecylerView.setVisibility(View.GONE);
    }

    private void setSearchView() {
        mSearchView.setVersion(com.lapism.searchview.SearchView.VERSION_MENU_ITEM);
        mSearchView.setVersionMargins(com.lapism.searchview.SearchView.VERSION_MARGINS_MENU_ITEM);
        mSearchView.setTextSize(16);
        mSearchView.setHint("搜索题目");
        mSearchView.setDivider(false);
        mSearchView.setVoice(false);
        mSearchView.setVoiceText("Set permission on Android 6+ !");
        mSearchView.setAnimationDuration(com.lapism.searchview.SearchView.ANIMATION_DURATION);
        mSearchView.setOnQueryTextListener(new com.lapism.searchview.SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                mSearchView.close(true);
                searchText = query.toString();
                mSwipeRefreshLayout.post(new Runnable() {
                    @Override
                    public void run() {
                        mSwipeRefreshLayout.setRefreshing(true);
                    }
                });
                getQuestionList();
                return true;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                return false;
            }
        });
    }

    @Override
    public void onLoadMore() {
        isLoadMore = true;
        if (!isRefreshOrLoadMore) {
            getQuestionList();
        }
    }

    public void getQuestionList() {
        if (isLoadMore) {  // 加载更多
            mStartIndex = mStartIndex + mSelectCount;
        } else { // 下拉刷新
            mStartIndex = 0;
        }
        questionListRequest(mStartIndex, mSelectCount, searchText);
    }

    private void questionListRequest(int startIndex, int selectCount, String searchText) {
        isRefreshOrLoadMore = true;
        mEmptyTv.setVisibility(View.GONE);
        JsonObjectRequest request = mRequest
                .questionListRequest(startIndex, selectCount, mExaminationId, PaperType.NONE, searchText,
                        new Response.Listener<JSONObject>() {
                            @Override
                            public void onResponse(JSONObject response) {
                                questionListener(response);
                            }
                        }, new Response.ErrorListener() {
                            @Override
                            public void onErrorResponse(VolleyError error) {
                                isRefreshOrLoadMore = false;
                                isLoadMore = false;
                                mRequest.disposeError(mContext, null, error, "获取题目列表失败");
                                mSwipeRefreshLayout.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        mSwipeRefreshLayout.setRefreshing(false);
                                    }
                                });
                                mQuestionRecylerView.setLoading(false);
                            }
                        });
        mQueue.add(request);
    }

    /**
     * 获取题目列表监听
     *
     * @param response
     */
    private void questionListener(JSONObject response) {
        int totalCount = 0;
        try {
            String resultCode = response.getString(Constant.RESULT_CODE);
            totalCount = response.getInt(Constant.TOTALCOUNT);
            if (resultCode.equals(ResultCode.result_ok.resultCode)) {
                JSONArray jsonArray = response
                        .getJSONArray(Constant.QUESTIONSLIST);
                Gson gson = new Gson();
                Type type = new TypeToken<List<Question>>() {
                }.getType();
                List<Question> questionListList = gson.fromJson(
                        jsonArray.toString(), type);
                if (questionListList == null || questionListList.size() == 0) {
                    mEmptyTv.setVisibility(View.VISIBLE);
                    mList.clear();
                }
                if (!isLoadMore) {
                    mList.clear();
                }
                mList.addAll(questionListList);
                mAdapter.notifyDataSetChanged();
            } else if (resultCode.equals(ResultCode.result_000001E.resultCode)) {
                MyToast.showShort(mContext, R.string.questionlib_09101_000001E);
            } else if (resultCode.equals(ResultCode.result_system_exception_999999E)) {
                MyToast.showShort(mContext, R.string.questionlib_091099_999999E);
            } else {
                MyToast.showShort(mContext, "获取题目列表失败");
            }
        } catch (Exception e) {
            LogUtil.e("Json异常", e);
            MyToast.showShort(mContext, "获取题目列表失败");
        } finally {
            isRefreshOrLoadMore = false;
            isLoadMore = false;
            mQuestionRecylerView.setLoading(false);
            mQuestionRecylerView.setVisibility(View.VISIBLE);
            mAdapter.notifyItemRangeInserted(0, mList.size() - 1);
            mSwipeRefreshLayout.post(new Runnable() {
                @Override
                public void run() {
                    mSwipeRefreshLayout.setRefreshing(false);
                }
            });
            if (mList.size() >= totalCount) {
                mQuestionRecylerView.setLoadMoreListener(null);
            } else {
                mQuestionRecylerView.setLoadMoreListener(this);
            }
        }
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            finishMenuActivity();
            return true;
        } else {
            return super.onKeyUp(keyCode, event);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    /**
     * 设置关闭activity的数据
     */
    private void finishMenuActivity() {
        IntentUtil.finishActivity(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mQueue.stop();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_question_list, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.question_search:
                mSearchView.open(true, item);
                return true;
            case R.id.question_upload:
                upLoadType = 0;
                mImageSelectHolder.open(mToolBar, ImageSelectHolder.IMAGE_QUESTION);
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        try {
            if (resultCode == RESULT_OK) {
                if (requestCode == ImageSelectHolder.REQUEST_SELECT_PICTURE || requestCode == ImageSelectHolder.CAMERA_WITH_DATA) {
                    Uri selectedUri = null;
                    if (data == null) {
                        selectedUri = Uri.fromFile(mImageSelectHolder.mTempFile);
                        mImageSelectHolder.startCropActivity(selectedUri);
                    } else {
                        selectedUri = data.getData();
                        if (selectedUri != null) {
                            mImageSelectHolder.startCropActivity(data.getData());
                        } else {
                            selectedUri = Uri.fromFile(mImageSelectHolder.mTempFile);
                            mImageSelectHolder.startCropActivity(selectedUri);
                        }
                    }
                } else if (requestCode == UCrop.REQUEST_CROP) {
                    handleCropResult(data);
                } else if (requestCode == 0x600) {
                    mSwipeRefreshLayout.post(new Runnable() {
                        @Override
                        public void run() {
                            mSwipeRefreshLayout.setRefreshing(true);
                        }
                    });
                    mRefreshListener.onRefresh();
                } else if (requestCode == 0x140 || requestCode == 0x150) {
                    if (data.getBooleanExtra(IntentUtil.QUESTION_IS_UPDATE, false)) {
                        mSwipeRefreshLayout.post(new Runnable() {
                            @Override
                            public void run() {
                                mSwipeRefreshLayout.setRefreshing(true);
                            }
                        });
                        mRefreshListener.onRefresh();
                    }
                }
            }
            if (resultCode == UCrop.RESULT_ERROR) {
                mImageSelectHolder.handleCropError(data);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void handleCropResult(@NonNull Intent result) throws Exception {
        final Uri mCropUri = UCrop.getOutput(result);
        final Bitmap photoBitmap;
        try {
            if (mCropUri != null) {
                photoBitmap = BitmapFactory.decodeStream(this
                        .getContentResolver().openInputStream(mCropUri));
                if (upLoadType == 0) {  // 题目上传
                    ImageSelectHolder.isDisable = false;
                    Intent intent = new Intent(QuestionListActivity.this,
                            QuestionUploadActivity.class);
                    intent.putExtra(IntentUtil.EXAMINATION_ID, mExaminationId);
                    intent.putExtra(IntentUtil.QUESTION_UPLOAD_URL, mCropUri);
                    startActivityForResult(intent, 0x600);
                } else {   // 题目图片增加
                    mAdapter.uploadImage(photoBitmap);
                }
            } else {
                Toast.makeText(this, "裁剪图片失败！", Toast.LENGTH_LONG)
                        .show();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (ImageSelectHolder.isDisable) {
                if (ImageSelectHolder.mTempFile != null && ImageSelectHolder.mTempFile.exists()) {
                    mImageSelectHolder.mTempFile.delete();
                }
                if (mCropUri != null) {
                    File cropFile = new File(mCropUri.getPath());
                    if (cropFile != null && cropFile.exists()) {
                        cropFile.delete();
                    }
                }
            }
        }
    }

}